package com.se.optionView;

import com.se.common.ConnectionType;
import com.se.common.Message;
import com.se.common.MessageType;
import com.se.common.User;
import com.se.utils.ClientUtils;
import com.se.utils.ServiceUtils;
import com.se.utils.StageManager;
import com.se.utils.StageType;
import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ListChangeListener;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.io.IOException;
import java.net.URL;
import java.util.Objects;
import java.util.ResourceBundle;
import java.util.concurrent.atomic.AtomicReference;

import static com.se.common.Constant.ONLINE;

public class AddFriendController implements Initializable {
    private static AddFriendController instance;

    public AddFriendController() {
        instance = this;
    }

    public static AddFriendController getInstance() {
        return instance;
    }

    @FXML
    public ListView<User> userSearchList;

    @FXML
    public TextField txfKeyword;

    @FXML
    public Button btnSearch;

    @FXML
    public Button btnClose;

    @FXML
    public StackPane resultListContainer;

    @FXML
    public ImageView resultBackground;

    @FXML
    public AnchorPane utilsPane;

    private final ObservableList<User> results = FXCollections.observableArrayList();

    @Override
    public void initialize(URL url, ResourceBundle resourceBundle) {
        AtomicReference<Double> offsetX = new AtomicReference<>((double) 0);
        AtomicReference<Double> offsetY = new AtomicReference<>((double) 0);
        utilsPane.setOnMousePressed(event -> {
            offsetX.set(event.getSceneX());
            offsetY.set(event.getSceneY());
        });

        utilsPane.setOnMouseDragged(event -> {
            Stage stage = StageManager.get(StageType.ADD_FRIEND_STAGE);
            stage.setX(event.getScreenX() - offsetX.get());
            stage.setY(event.getScreenY() - offsetY.get());
        });

        btnSearch.getStylesheets().add(Objects.requireNonNull(getClass().getResource("/com/se/css/search-button.css")).toExternalForm());

        resultListContainer.getStylesheets().add(Objects.requireNonNull(getClass().getResource("/com/se/css/result-list-view.css")).toExternalForm());

        btnClose.getStylesheets().add(Objects.requireNonNull(getClass().getResource("/com/se/css/close-button.css")).toExternalForm());
        resultBackground.fitHeightProperty().bind(resultListContainer.heightProperty());
        resultBackground.fitWidthProperty().bind(resultListContainer.widthProperty());

        btnSearch.setDisable(true);
        userSearchList.setItems(results);
        userSearchList.setCellFactory(cell -> new SearchResultCell());
        txfKeyword.lengthProperty().addListener((obs, oldVal, newVal) ->
                btnSearch.setDisable(newVal.intValue() == 0));
        results.addListener((ListChangeListener<User>) change ->
                resultBackground.setVisible(results.isEmpty()));
    }

    public static class SearchResultCell extends ListCell<User> {
        @Override
        public void updateItem(User item, boolean empty) {
            super.updateItem(item, empty);

            // 清空单元格内容
            setText(null);
            setGraphic(null);

            if (item == null || empty) return;

            // 主容器使用HBox替代BorderPane
            HBox container = new HBox();
            container.setSpacing(10);
            container.setAlignment(Pos.CENTER_LEFT);
            container.setPadding(new Insets(5));

            // 左侧内容容器
            HBox contentBox = new HBox(5);
            contentBox.setAlignment(Pos.CENTER_LEFT);

            // 状态图标
            ImageView statusIcon = createStatusIcon(item.getStatus());

            // 用户名标签
            Label nameLabel = new Label(item.getUserName());
            nameLabel.getStyleClass().add("result-label");
            nameLabel.setStyle("-fx-font-size: 14px;");

            // 添加按钮（右侧对齐）
            Button addButton = createAddButton(item);
            for(var i : ServiceUtils.getUserList()) {
                if(i.getUserName().equals(item.getUserName())) {
                    addButton.setDisable(true);
                    break;
                }
            }

            // 弹性填充区域
            Region spacer = new Region();
            HBox.setHgrow(spacer, Priority.ALWAYS);

            // 组装布局
            contentBox.getChildren().addAll(statusIcon, nameLabel);
            container.getChildren().addAll(contentBox, spacer, addButton);

            setGraphic(container);
        }

        private ImageView createStatusIcon(String status) {
            String path = ONLINE.equals(status)
                    ? "/image/online.png"
                    : "/image/offline.png";

            Image image = new Image(Objects.requireNonNull(
                    getClass().getResource(path)).toString()
            );

            ImageView icon = new ImageView(image);
            icon.setFitWidth(20);
            icon.setFitHeight(20);
            return icon;
        }

        private Button createAddButton(User user) {
            Button button = new Button("添加");
            button.getStylesheets().add(Objects.requireNonNull(getClass().getResource("/com/se/css/add-friend-button.css")).toExternalForm());

            button.setOnAction(event -> {
                handleAddFriend(user);
                button.setDisable(true);
            });
            return button;
        }

        private void handleAddFriend(User targetUser) {
            Message message = new Message();
            message.setMsgType(MessageType.MESSAGE_ADD_FRIEND);
            message.setSendUser(ServiceUtils.getSpeaker().getUserName());
            message.setReceiveUser(targetUser.getUserName());

            try {
                ClientUtils.sendMessage(
                        ServiceUtils.getConnection(ConnectionType.BASE_CONNECTION).getSocket(),
                        message
                );
            } catch (IOException e) {
                // 建议添加更完善的错误处理
                System.err.println("添加好友请求发送失败: " + e.getMessage());
            }
        }
    }

    @FXML
    public void btnSearchOnClick() {
        results.clear();
        Message message = new Message();
        message.setContent(txfKeyword.getText());
        message.setSendUser(ServiceUtils.getSpeaker().getUserName());
        message.setMsgType(MessageType.MESSAGE_SEARCH_FRIEND);
        try {
            ClientUtils.sendMessage(ServiceUtils
                    .getConnection(ConnectionType.BASE_CONNECTION).getSocket(), message);
        } catch (IOException e) {
            /*
            异常处理待优化
             */
            e.printStackTrace();
        }
    }

    @FXML
    public void btnCloseOnClick() {
        if(StageManager.get(StageType.ADD_FRIEND_STAGE) != null) {
            StageManager.get(StageType.ADD_FRIEND_STAGE).close();
            StageManager.remove(StageType.ADD_FRIEND_STAGE);
        }
    }

    @FXML
    public void addResult(User item) {
        Platform.runLater(() -> results.add(item));
    }
}
